import {defHttp} from '@/utils/request';
import type {AxiosProgressEvent, GenericAbortSignal} from 'axios'

export namespace chatMessageApi {
	// 发送消息
	export function send(
		params: {
			prompt: string
			options?: { conversationId?: string; parentMessageId?: string }
			signal?: GenericAbortSignal
			onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void
		},
	) {
		return defHttp.post({
			url: '/api/chat_message/send',
			data: {
				prompt: params.prompt,
				options: params.options,
			},
			signal: params.signal,
			onDownloadProgress: params.onDownloadProgress,
		})
	}

	// 字符需要特殊处理下，否则会解析异常
	const getChatMessageSplitKey = () => {
		return '☉#$open_ai$#☉'
	}

	// 解析响应报文
	export function parseChunk(responseText: string) {
		try {
			const splitKey = getChatMessageSplitKey()
			const lastIndex = responseText.lastIndexOf(splitKey, responseText.length - 2)
			let chunk = responseText
			if (lastIndex !== -1) {
				chunk = responseText.substring(lastIndex + splitKey.length)
				chunk = "\"" + chunk
			}
			// console.log(chunk)
			return JSON.parse(JSON.parse(chunk));
		} catch (e: any) {
			console.log(e)
			return "数据出错啦"
		}

	}

}

